package com.tma.internship.activities;

import java.io.FileInputStream;
import java.io.Serializable;
import java.util.List;
import com.tma.internship.ClassesInfo.CommentInfo;
import com.tma.internship.ClassesInfo.ControlBookMark;
import com.tma.internship.ClassesInfo.FileInfo;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.ViewFlipper;

public class ViewBookActivity extends Activity {
	private ViewFlipper flip;
	private String fileName;
	private FileInfo fInfo;
	
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		
		setContentView(R.layout.view_page_image);
		flip = (ViewFlipper) findViewById(R.id.flip);
		flip.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
		flip.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));
		fInfo = (FileInfo) getIntent().getSerializableExtra("file");
		fileName = fInfo.getName();
		page = fInfo.getNumOfPage();
		int pageBookmark;
		pageBookmark = getIntent().getIntExtra("page", 0);
		goTo(pageBookmark);
	}
	private void goTo(int pageBookmark){
		
		if (pageBookmark > 0) pageBookmark--;
		int length = fInfo.getNumOfPage()> BUFF_SIZE ? BUFF_SIZE : fInfo.getNumOfPage();
		try {
			for (int i = 0 ; i < length ; i++){
				if (i < length - 1){
					int index = (pageBookmark + i) % page;
					FileInputStream fin = this.openFileInput(fInfo.getName()+"_"+index+".png");
					BitmapDrawable draw = new BitmapDrawable(fin);
					TouchImageView img = new TouchImageViewIml(this);
					img.setImage(draw.getBitmap());
					flip.addView(img);
					currNextPage = index;
				} else {
					int index = pageBookmark - 1 >= 0 ? pageBookmark - 1 : page - 1;
					FileInputStream fin = this.openFileInput(fInfo.getName()+"_"+index+".png");
					BitmapDrawable draw = new BitmapDrawable(fin);
					currPreviousPage = index;
					TouchImageView img = new TouchImageViewIml(this);
					img.setImage(draw.getBitmap());
					flip.addView(img);
				}
			}
		} catch (Exception e){
			e.printStackTrace();
		}
		curr = pageBookmark + 1;
		setTitle(curr+ "/"+page);
	}
	private int currNextPage;
	private int currPreviousPage;
	private int curr;
	private int page;
	private void next() throws Exception{
		currNextPage = (currNextPage + 1) % page;
		currPreviousPage = (currPreviousPage + 1) % page;
		curr = curr % page + 1;
		if (page >= BUFF_SIZE){
			Log.d("curr", currNextPage+"");
			FileInputStream fin = this.openFileInput(fInfo.getName()+"_"+currNextPage+".png");
			BitmapDrawable draw = new BitmapDrawable(fin);
			flip.setInAnimation(inFromRightAnimation());
			flip.setOutAnimation(outToLeftAnimation());
			flip.showNext();
			int index = flip.indexOfChild(flip.getCurrentView());
			int nextIndex = (index + 1) % BUFF_SIZE;
			((TouchImageView) flip.getChildAt(nextIndex)).setImage(draw.getBitmap());
			((TouchImageView) flip.getCurrentView()).center();
		} else 
		{
			flip.setInAnimation(inFromRightAnimation());
			flip.setOutAnimation(outToLeftAnimation());
			flip.showNext();
			((TouchImageView) flip.getCurrentView()).center();
			
		}
		setTitle((curr)+ "/"+page);
	}
	private void previous() throws Exception{
		currNextPage = (currNextPage - 1 + page) % page;
		currPreviousPage = (currPreviousPage - 1 + page) % page;
		curr = curr - 1;
		if (curr == 0) curr = page;
		if (page >= BUFF_SIZE){
			FileInputStream fin = this.openFileInput(fInfo.getName()+"_"+currPreviousPage+".png");
			BitmapDrawable draw = new BitmapDrawable(fin);
			flip.setInAnimation(inFromLeftAnimation());
			flip.setOutAnimation(outToRightAnimation());
			flip.showPrevious();
			int index = flip.indexOfChild(flip.getCurrentView());
			int previousIndex = (index - 1 + BUFF_SIZE) % BUFF_SIZE;
			((TouchImageView) flip.getChildAt(previousIndex)).setImage(draw.getBitmap());
			((TouchImageView) flip.getCurrentView()).center();
		} else {
			flip.setInAnimation(inFromLeftAnimation());
			flip.setOutAnimation(outToRightAnimation());
			flip.showPrevious();
			((TouchImageView) flip.getCurrentView()).center();
		}
		setTitle((curr)+ "/"+page);
		
	}
	private int BUFF_SIZE = 3;
	private boolean isTouching = false;
	private float touch;
	private static final float MOVE_SIZE = 80;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		int action = event.getAction();
		if (action == MotionEvent.ACTION_DOWN){
			isTouching = true;
			touch = event.getX();
		} else if (action == MotionEvent.ACTION_UP){
			try {
				if (isTouching){
					float touch2 = event.getX();
					if (touch - touch2 >= MOVE_SIZE)
					{
						next();
					} else if (touch2 - touch >= MOVE_SIZE){
						previous();
					}
				}
			} catch (Exception e){
				e.printStackTrace();
			}
			isTouching = false;
		}
		return super.onTouchEvent(event);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.view_book_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()){
			case R.id.book_mark_item:
				new BookmarkDialog(this, fileName, curr).show();
				return true;
			case R.id.list_bookmark:
				ControlBookMark ctr = new ControlBookMark(this);
				List<CommentInfo> listCmtInfos = ctr.listCmtInBook(fileName);
				Intent intent = new Intent(this,BookmarkActivity.class);
				//Log.d("list", listCmtInfos.get(0).getTime());
				if (listCmtInfos!= null) for (CommentInfo cmt:listCmtInfos){
					cmt.setfInfo(fInfo);
				}
				intent.putExtra("list", (Serializable) listCmtInfos);
				intent.putExtra("book",fileName);
				startActivity(intent);
				return true;
			case R.id.go_to:
				new GoToPageDlg(this) {
					
					@Override
					public void goToPage(int page) {
						// TODO Auto-generated method stub
						flip.removeAllViews();
						goTo(page);
					}
				}.show(page);
			default:return super.onMenuItemSelected(featureId, item);
		}
		
	}
	
	
	private Animation inFromRightAnimation() {
			Animation inFromRight = new TranslateAnimation(
			Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
			Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
			);
			inFromRight.setDuration(300);
			inFromRight.setInterpolator(new AccelerateInterpolator());
			return inFromRight;
		}
		private Animation outToLeftAnimation() {
			Animation outtoLeft = new TranslateAnimation(
			  Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
			  Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
			);
			outtoLeft.setDuration(300);
			outtoLeft.setInterpolator(new AccelerateInterpolator());
			return outtoLeft;
		}
		 
		private Animation inFromLeftAnimation() {
			Animation inFromLeft = new TranslateAnimation(
			Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
			Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
			);
			inFromLeft.setDuration(300);
			inFromLeft.setInterpolator(new AccelerateInterpolator());
			return inFromLeft;
		}
		private Animation outToRightAnimation() {
			Animation outtoRight = new TranslateAnimation(
			  Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
			  Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
			);
			outtoRight.setDuration(300);
			outtoRight.setInterpolator(new AccelerateInterpolator());
			return outtoRight;
		}
		
		private class TouchImageViewIml extends TouchImageView {

			public TouchImageViewIml(Context context) {
				super(context);
				// TODO Auto-generated constructor stub
			}

			@Override
			public void moveNext() {
				// TODO Auto-generated method stub
				try {
					next();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void movePrevious() {
				// TODO Auto-generated method stub
				try {
					previous();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
}